<template>
  <el-container class="ai-exam-page">
    <el-header>
      <Head :title="state.bot.name" :text="state.rightExt.chatTitle" @back="goBack" />
    </el-header>
    <el-container>
      <SidebarPanel
        ref="sidebarPanelRef"
        :collapsed="sidebarCollapsed"
        :addNew="newSpeak"
        @toggle="sidebarCollapsed = !sidebarCollapsed"
        @getId="getLogId"
        @removeId="removeLogId"
      />
      <el-main class="main">
        <!-- 关键词填写 -->
        <LessonPlanningVue
          v-if="current == 0"
          :prompts="prompts || []"
          :botId="botId"
          :rightExt="state.rightExt"
          :subjectList="state.subjectList"
          :gradeList="state.gradeList"
          :versionList="state.versionList"
          @query="lessonQuery"
        />
        <!-- 对话 -->
        <CenterPanel
          ref="centerPanelRef"
          @aiAnswerOrer="aiAnswerOrer"
          v-if="current == 1"
          :selectId="logId"
          :conversationId="state.conversation_id"
          :list="state.list"
          :exts="state.rightExt"
          :fileList="state.fileList"
          :loadAudioNum="state.loadAudioNum"
          :prompts="state.values"
          :isEnd="state.isEnd"
          :loading="state.loading"
          :catalogTitle="state.catalogTitle"
          :avatar="state.bot.avatar"
        />
      </el-main>
      <el-aside width="360px" style="border: 1px solid red" v-if="state.rightExt.rightType">
        留着看看可以干点啥
      </el-aside>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import SidebarPanel from '@/components/sidebarPanel/index.vue';
import CenterPanel from '@/components/centerPanel/index.vue';
import LessonPlanningVue from '@/components/centerPanel/lessonPlanning.vue';

import Head from '@/components/head/index.vue';
import _ from 'lodash';
import { reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

import { useAppStore } from '@/store/modules/app';
import { api } from '@/utils/request';
import details from '@/faker/byBotId';
import { useFetchStream } from '@/hooks/useFetchStream';

const appStore = useAppStore();
// 是否在生成中
const chatActive = computed(() => appStore.chatActive);

const current = ref(0);
const centerPanelRef = ref();
const sidebarPanelRef = ref();

const sidebarCollapsed = ref(false);

const router = useRouter();
const route = useRoute();

const { id: botId, flag = '' } = route.query as {
  id: string;
  logId: string;
  flag: string;
  linkUrl: string;
};

const state = reactive({
  list: [] as any[],
  loading: false,
  leftLoading: false,
  bot: {} as any,
  values: [] as string[],
  flag,
  conversation_id: '',
  task_id: '',
  linkUrl: '',
  fileList: [] as any,
  loadAudioNum: '0',
  isEnd: true,
  subjectList: [] as any,
  versionList: [] as any,
  gradeList: [] as any,
  catalogTitle: '',
  rightExt: {} as any,
  filePaths: '',
  wolds: 'txt,doc,docx,pdf,ppt,pptx,xlsx,xls',
  imgs: 'jpg,jpeg,png,gif,webp,svg',
  audios: 'mp3,m4a,wav,webm,amr',
  videos: 'mp4,mov,mpeg,mpga',
  newNums: -1,
  currentAnswer: {} as any,
  isShengCheng: false,
});

const prompts = computed(() => {
  const { prompt } = state.bot;
  return prompt;
});

// 新建对话
let message = ElMessage;
const newSpeak = () => {
  if (chatActive.value) {
    ElMessage.error('请等待生成结果');
    return;
  }
  state.list = [];
  logId.value = '';
  state.fileList = [];
  state.conversation_id = '';
  if (message) message.closeAll();
  message = ElMessage;
  if (current.value === 0) return ElMessage.warning('当前已经在新会话界面！');

  if (centerPanelRef.value) {
    centerPanelRef.value.newSpeak(next);
  } else {
    next(0);
  }
};

// 选择完
const lessonQuery = async (form: any, files: any) => {
  state.values = form;
  state.filePaths = files;
  state.isEnd = true;
  messageGet();
  state.newNums = 1;
  next(1);
};

const next = (num: number) => {
  current.value = num;
};

// ai 回答完
const aiAnswerOrer = (id: any) => {
  if (sidebarPanelRef.value) {
    setTimeout(() => {
      sidebarPanelRef.value.getChat(id);
    }, 1500);
  }
};

const goBack = async () => {
  router.go(-1);
};

// 获取选择的机器人详情
const getBot = async () => {
  state.leftLoading = true;
  const data: any = details.find(v => v.id === botId);
  state.leftLoading = false;
  state.bot = data;
  if (data.ext) {
    state.rightExt = JSON.parse(data.ext);
    state.flag = state.bot.flag;
  }
};

const onEnded = async () => {
  state.currentAnswer = {};
  state.isShengCheng = false;
  state.isEnd = false;
};

const messageGet = async () => {
  if (state.isShengCheng) {
    // 生成过程中不能再次生成
    return false;
  }
  // 封装成对应格式
  let inputs = {} as any;
  let query: string = '';

  prompts.value.forEach((fe: any, index: number) => {
    // 用户输入的 query
    if (fe[1] === 'input') {
      query = fe[5];
    } else {
      // inputs
      inputs[fe[1]] = state.values[index];
    }
  });
  // 拼接处理参数
  let args = {
    query,
    user: appStore.user.id,
    botId,
    inputs,
    filePaths: state.filePaths,
  } as any;
  // 是否结合上下文
  if (state.conversation_id) {
    args = { ...args, conversation_id: state.conversation_id };
  }
  state.loading = true;

  dispatch(args);
};

// 通用流
const chatSendContent = async (args: any) => {
  const apiUrl = args.api || '/chat/chat-stream';
  const params = {
    onMessage: (data: any) => {
      let { event: type, answer: content, conversation_id, task_id } = data || {};
      // 流传输中
      console.log('type ====> ', type);
      if (type === 'message') {
        state.conversation_id = conversation_id;
        state.task_id = task_id;
        if (!state.list[0]) state.list[0] = { answer: '' };
        state.list[0].answer += content;
      }
      // 结束了, 这个可以添加log记录
      if (type === 'message_end') {
        onEnded();
        state.loading = false;
      }
    },

    onError: (err: any) => {
      throw err;
    },

    onClose: () => {
      state.loading = false;
    },
  };

  useFetchStream(`${api}/${apiUrl}`, args, params);
};

// 方法调度中心
const dispatch = (args: any) => {
  const { ext } = state.bot;

  const { botFlag } = JSON.parse(ext);
  // 试题解析
  if (botFlag === '11') {
    args.inputs.files = [
      {
        type: 'image',
        transfer_method: 'remote_url',
        url: 'https://cdn.henanyuexue.com/dify/bot/93c61722ae9b41399a8d505d065a94c2/fGA1751514460537.png',
      },
    ];
    args.api = '/chat/chat-analysis';
    chatSendContent(args);
  } else {
    chatSendContent(args);
  }
};

const logId = ref('');
const getLogId = (id: any) => {
  logId.value = id;
  next(1);
};

const removeLogId = (id: any) => {
  if (logId.value === id) {
    logId.value = '';
    next(0);
  }
};

onMounted(async () => {
  const { showAside = true } = route.query;
  Promise.all([getBot()]);
  // 兼容预览机器人
  if (showAside === 'false') {
    const aside = document.getElementsByClassName('el-aside')[0] as any;
    aside.style.display = 'none';
    // back-icon
    const back = document.getElementsByClassName('back-icon')[0] as any;
    back.style.display = 'none';
  }
});
</script>

<style scoped lang="scss">
@use './index.scss';
</style>
